/**

 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.github.cakin.shiro.chapter22.jcaptcha;

import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.captchastore.FastHashMapCaptchaStore;

import javax.servlet.http.HttpServletRequest;

/**
 * @className: JCaptcha
 * @description: 提供相应的 API 来验证当前请求输入的验证码是否正确
 * @date: 2020/5/30
 * @author: cakin
 */
public class JCaptcha {
    public static final MyManageableImageCaptchaService captchaService
            = new MyManageableImageCaptchaService(new FastHashMapCaptchaStore(), new GMailEngine(), 180, 100000, 75000);

    /**
     * 功能描述：验证session和验证码是否匹配
     *
     * @author cakin
     * @date 2020/5/30
     * @param request 请求
     * @param userCaptchaResponse 验证码
     * @return boolean 验证是否成功
     */
    public static boolean validateResponse(HttpServletRequest request, String userCaptchaResponse) {
        if (request.getSession(false) == null) return false;

        boolean validated = false;
        try {
            String id = request.getSession().getId();
            // 验证当前请求输入的验证码否正确；并从 CaptchaService 中删除已经生成的验证码
            // session和验证码要匹配
            validated = captchaService.validateResponseForID(id, userCaptchaResponse).booleanValue();
        } catch (CaptchaServiceException e) {
            e.printStackTrace();
        }
        return validated;
    }

    public static boolean hasCaptcha(HttpServletRequest request, String userCaptchaResponse) {
        if (request.getSession(false) == null) return false;
        boolean validated = false;
        try {
            String id = request.getSession().getId();
            validated = captchaService.hasCapcha(id, userCaptchaResponse);
        } catch (CaptchaServiceException e) {
            e.printStackTrace();
        }
        return validated;
    }

}
